package com.gmcc.docmanager;

import com.gmcc.docmanager.app.Constants;

import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class BaseListActivity extends ListActivity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.ACTION_CLOSE_ACTIVITY);
		filter.addAction(Constants.ACTION_BACK_TO_HOME_ACTIVITY);
		registerReceiver(mCloseActivityReceiver, filter);
	}

	@Override
	protected void onDestroy() {
		if (mCloseActivityReceiver != null) {
			unregisterReceiver(mCloseActivityReceiver);
			mCloseActivityReceiver = null;
		}
		super.onDestroy();
	}

	public void closeActivity(String className) {
		Intent broadcastIntent = new Intent(Constants.ACTION_CLOSE_ACTIVITY);
		broadcastIntent.putExtra("className",
				Constants.ACTION_BACK_TO_HOME_ACTIVITY);
		sendBroadcast(broadcastIntent);
	}

	public void backToHomeActivity() {
		Intent broadcastIntent = new Intent(Constants.ACTION_BACK_TO_HOME_ACTIVITY);
		sendBroadcast(broadcastIntent);
	}

	private BroadcastReceiver mCloseActivityReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (intent.getAction().equals(Constants.ACTION_CLOSE_ACTIVITY)) {
				String className = intent.getStringExtra("className");
				if (LoginActivity.class.getName().equals(className)) {
					if (mCloseActivityReceiver != null) {
						unregisterReceiver(mCloseActivityReceiver);
						mCloseActivityReceiver = null;
					}
					finish();
				}
			} else if (Constants.ACTION_BACK_TO_HOME_ACTIVITY.equals(action)) {
				Intent mainintent = getIntent();
				String act = mainintent.getAction();
				if (!Intent.ACTION_MAIN.equals(act)) {
					if (mCloseActivityReceiver != null) {
						unregisterReceiver(mCloseActivityReceiver);
						mCloseActivityReceiver = null;
					}
					finish();
				}
			}
		}
	};
}
